<template>
  <div style="height: 50px">
    <!--顶部导航栏-->
    <nav id="nav" class="navbar navbar-expand-md" style="height: 50px;z-index: 999">

      <div class="nav-content ">
        <!--左侧区域-->
        <ul class="navbar-nav title">
          <!--logo-->
          <div style="margin-right: 25px;cursor: pointer" class="logo">
            <img :src="require(`@/assets/static/img/favicon.png`)" alt="logo" width="40px">
          </div>
          <li class="nav-item">
            <router-link to="/" class="nav-link">数码商城系统</router-link>
          </li>
          <li class="nav-item">
            <el-button @click="goto('/',$event.target)" type="success" icon="el-icon-s-home" size="small" plain circle></el-button>
          </li>
        </ul>

        <!--搜索框-->
        <div :class="isLogin ? 'search-wrap' : ''">
          <el-autocomplete
                  clearable
                  class="inline-input"
                  v-model="searchKeyWord"
                  @keyup.native.enter="search"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="">
          </el-autocomplete>
          <el-button @click="search" icon="el-icon-search" size="medium" circle style="margin-left: 5px"></el-button>
        </div>

        <!--右侧区域-->
        <ul class="nav navbar-nav" ><!--style="margin-left: auto"-->
          <template v-if="isLogin">
            <li class="nav-item">
              <el-button type="success" icon="el-icon-s-home" size="small" plain circle
                         @click="goto('/',$event.target)"></el-button>
              <el-button type="success" icon="el-icon-rank" size="small" plain @click="goto('/home/address',$event.target)">地址管理</el-button>

              <el-button type="primary" icon="el-icon-shopping-cart-2" size="small" plain @click="goto('/shoppingCart',$event.target)">购物车</el-button>
              <el-button type="primary" icon="el-icon-s-order" size="small" plain @click="goto('/order',$event.target)">订单</el-button>

            </li>

            <li class="nav-item avatar-li" >
              <!--头像-->
              <div class="avatar"  @mouseenter="avatarFlag=true" @mouseleave="avatarFlag=false">
                <transition name="avatar-small">
                  <img src="../../assets/static/img/index_avatar.png" v-show="!avatarFlag">
                </transition>
                <transition name="avatar">
                  <!--头像二级菜单-->
                  <div class="menu avatar-menu" v-show="avatarFlag">
                    <div class="avatar-menu-img">
                      <img src="../../assets/static/img/index_avatar.png">
                    </div>
                    <div class="avatar-menu-content">
                      <p class="name">{{ nickname }}</p>

                      <span class="identity">年度会员</span>
                      <div class="level">
                        <el-link :underline="false">等级5</el-link>
                        <span style="color: grey;font-size: 10px;">9999/N</span>
                      </div>
                      <div class="level-bar">
                        <div class="level-progress"></div>
                      </div>

                      <div class="btn-content">
                        <el-button  @click="getInfo" type="success" size="small" plain>修改个人信息</el-button>

                        <el-button  @click="passwordDialog = true" type="primary" size="small" plain>修改密码</el-button>
                        <el-button  @click="" type="warning" size="small" plain>待定</el-button>
                        <el-button  @click="" type="danger" size="small" plain>待定</el-button>

                        <el-button type="primary" size="small">主要按钮</el-button>
                      </div>
                    </div>
                  </div>

                </transition>
              </div>
            </li>
          </template>

          <li class="nav-item">
            <!--导航栏右-退出区-->
            <div class="cancel">
              <button v-if="!isLogin"
                      @click="login"  @mouseenter="loginAndLogout=true" @mouseleave="loginAndLogout=false">登录</button>

              <template v-else>
                <el-popconfirm
                        confirm-button-text='好的'
                        cancel-button-text='不用了'
                        icon="el-icon-info"
                        icon-color="red"
                        title="是否退出账户？"
                        @confirm="logout()">>
                  <button slot="reference"   @mouseenter="loginAndLogout=true" @mouseleave="loginAndLogout=false">退出</button>

                </el-popconfirm>
              </template>

              <!--退出二级菜单-->
              <transition name="slide-fade">
                <div class="menu cancel-menu" v-show="loginAndLogout">
                  <div v-if="!isLogin">快快登录吧</div>
                  <div v-if="isLogin">欢迎下次光临</div>
                </div>
              </transition>
            </div>
          </li>
        </ul>
      </div>
    </nav>


    <!--修改密码dialog-->
    <!-- :modal-append-to-body='false' -->
    <el-dialog title="修改密码" :visible.sync="passwordDialog" :before-close="handleClose" :append-to-body="true" width="30%">
      <el-form :model="modifyPasswordForm" :rules="rules" ref="modifyPasswordForm" style="width: 80%" label-width="100px">
        <el-form-item label="原密码" prop="password">
          <el-input v-model="modifyPasswordForm.password" show-password prefix-icon="el-icon-edit"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="modifyPasswordForm.newPassword" show-password prefix-icon="el-icon-magic-stick"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="modifyPasswordForm.confirmPassword" show-password prefix-icon="el-icon-warning"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('modifyPasswordForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!--修改个人信息dialog-->
    <el-dialog title="修改个人信息" :visible.sync="modifyInfoDialog" :before-close="handleClose" :append-to-body="true" width="30%">
      <div v-loading="loading" element-loading-text="拼命加载中" element-loading-body="true">
        <el-form :model="modifyInfoForm" :rules="rules" ref="modifyInfoForm" style="width: 80%" label-width="100px">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="modifyInfoForm.nickname" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="modifyInfoForm.phone" prefix-icon="el-icon-phone-outline"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="modifyInfoForm.email" prefix-icon="el-icon-platform-eleme"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <el-input v-model="modifyInfoForm.avatar" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="modifyInfoForm.gender" size="medium">
              <el-radio-button label="1">男</el-radio-button>
              <el-radio-button label="2">女</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
                    v-model="modifyInfoForm.birthday"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyInfoDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('modifyInfoForm')">确 定</el-button>
      </div>

    </el-dialog>

  </div>

</template>

<script>
  import { mapGetters } from 'vuex'
  import { getUserBasicInfo, updateUserBasicInfo, modifyPasswordReq} from "@/api/index";
  export default {
    name : "my-header",
    components:{},
    data() {
      let validatePassword = (rule, value, callback) => {
        if (value !== this.modifyPasswordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return{
        loading: true,

        searchKeyWord: "",
        //searchHistoryData:[],

        //user:{name:"张三"},//存储从sessionStorage获取的user
        avatarFlag : false,//控制头像二级菜单
        loginAndLogout : false,//控制退出二级菜单
        passwordDialog : false,//控制修改密码表单弹窗


        modifyPasswordForm : {//修改密码表单
          password : '',
          newPassword : '',
          confirmPassword : '',
        },
        modifyInfoDialog : false,//控制个人信息表单弹窗
        modifyInfoForm : {//修改个人信息表单
          nickname : '',
          phone : '',
          email : '',
          avatar : '',
          gender : 0,
          birthday : '',
        },
        rules: {//修改密码验证规则
          nickname: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          email: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          phone: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            { pattern: /^1[34578]\d{9}$/, message: '请输入正确的中国大陆的手机号码', trigger: ['blur', 'change']},
          ],

          password: [
            { required: true, message: '请输入原密码', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' }
          ],
          newPassword: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' }
          ],
          confirmPassword: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' },
            { validator: validatePassword, message: '密码不一致 ', trigger: 'blur' }
          ],
        }
      }
    },
    methods : {
      goto(page,event){
        this.$router.push(page);
        if(event.nodeName === 'SPAN' || event.nodeName === 'I'){
          event = event.parentNode;
        }
        event.blur();
      },
      login(){
        console.log("登陆")
        this.$router.push('/login')
      },
      logout(){
        this.$store.dispatch('user/logout')
        this.$router.push('/')
      },
      /*候选输入类*/
      search(){
        if(this.searchKeyWord === "") return;
        let localStorageData = JSON.parse(localStorage.getItem("searchHistoryData")) || []

        let flag = false
        localStorageData.forEach(item => {
          if (item.value === this.searchKeyWord) flag = true;
        })
        if (!flag){
          if (localStorageData.length >= 5){
            this.searchHistoryData.pop();
            this.searchHistoryData.unshift({value: this.searchKeyWord});
          }else {
            this.searchHistoryData.unshift({value: this.searchKeyWord});
          }
        }
        //console.log("search里添加后的searchHistoryData =", this.searchHistoryData)
        localStorage.setItem("searchHistoryData", JSON.stringify(this.searchHistoryData))
        this.$router.push(`/search/${this.searchKeyWord}`)
      },
      querySearch(queryString, cb) {
        let searchData = this.searchHistoryData;
        let results = queryString ? searchData.filter(this.createFilter(queryString)) : searchData;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        console.log(queryString)
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleClose(done) {
        this.$confirm('确认关闭？').then(_ => {done();}).catch(_ => {});
      },
      /*修改个人信息*/
      getInfo(){
        this.modifyInfoDialog = true;//打开修改信息的弹窗
        this.loading = true;//进入加载
        //根据用户id查询个人信息
        getUserBasicInfo().then(response => {
          console.log(response)
          if (response.state === true) {
            this.modifyInfoForm = response.data.user;//显示信息
            this.loading = false;//取消加载
            //this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else{
            this.$notify.warning({title: '失败',message: response.message, duration: 1500});
          }
        })
      },
      submitForm(formName) {//修改密码
        if (formName === "modifyInfoForm" && this.loading) {
          //如果是修改信息表单要先查询，等待loading状态结束
          console.log("还在加载中")
          return;
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (formName === "modifyInfoForm") {
              console.log(this.modifyInfoForm)
              updateUserBasicInfo(this.modifyInfoForm).then(response => {
                console.log(response)
                if (response.state === true) {
                  this.modifyInfoDialog = false//关闭弹窗
                  this.$store.commit("user/SET_NAME", this.modifyInfoForm.nickname)
                  this.$notify.success({title: '成功',message: response.message, duration: 1500});
                }else{
                  this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                }
              })
            }else if (formName === "modifyPasswordForm"){
              modifyPasswordReq({ modifyPasswordForm: this.modifyPasswordForm }).then(response => {
                console.log(response)
                if (response.state === true) {
                    this.passwordDialog = false//关闭弹窗
                    this.resetForm(formName);
                    this.$notify.success({title: '成功',message: response.message, duration: 1500});
                }else{
                  this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                }
              })
            }
          } else {
            this.$notify({title: '错误', message: '验证不通过', type: 'error'});
          }
        });
      },
      resetForm(formName){
        this.$refs[formName].resetFields();
      },
    },
    computed: {
      ...mapGetters(['token','nickname','avatar']),//数组写法

      isLogin(){
        return this.token != null;
      },
      searchHistoryData(){
        //console.log("searchHistoryData =",JSON.parse(localStorage.getItem("searchHistoryData")))
        return JSON.parse(localStorage.getItem("searchHistoryData")) || []
      }
    },
    beforeMount(){
    },
    mounted(){
      //console.log("isLogin =",this.$store.getters.isLogin)
      //console.log(this.$store.getters.user)
    },
  }
</script>

<style scoped src="@assets/static/css/head.css"></style>
<style scoped src="@assets/static/css/vue-transition.css"></style>

<style scoped>

  .search-wrap{
    position: relative;
    left: 100px;
  }
  .inline-input{
    width: 300px;
  }

  @media (max-width: 1300px){
    .search-wrap{
      left: 50px;
    }
  }

  @media (max-width: 1100px){
    .title,.cancel{
      display: none;
    }
  }

  @media (max-width: 1000px){
    .logo,.title,.cancel{
      display: none;
    }
    .inline-input{
      width: 200px;
    }
    .search-wrap{
      left: 10px;
    }
  }

</style>
